import requests
import os
from datetime import datetime
import json

class post_media:#录制视频和停止录制
    def __init__(self,id_stream):
        self.id_stream = id_stream
        self.url_ori="http://170.0.40.81:8080"
        self.headers = {'Content-type': 'application/json'}
        self.data={"secret": "035c73f7-bb6b-4889-a715-d9eb2d1925cc"}
        self.data_MediaList={"secret": "035c73f7-bb6b-4889-a715-d9eb2d1925cc","schema": "rtmp","app": "live"}
        self.startRecord='/index/api/startRecord'
        self.stopRecord='/index/api/stopRecord'
        self.getMp4RecordFile='/index/api/getMp4RecordFile'
        self.date_time=datetime.now()
        self.mp4_res=[]
    def start_media(self):
        self.date_time=datetime.now()
        data_json = json.dumps(self.data)   
        url=self.url_ori+self.getMp4RecordFile+'?vhost=__defaultVhost__&app=live&stream=stream'+str(self.id_stream)+'&period='+str(self.date_time.date())        
        response = requests.post(url, data=data_json, headers=self.headers)
        res=response.json()
        self.mp4_res=res['data']['paths'] #保存录制视频前mp4名字
        url=self.url_ori+self.startRecord+'?type=1&vhost=__defaultVhost__&app=live&stream=stream'+str(self.id_stream)
        response = requests.post(url, data=data_json, headers=self.headers)
    def stop_media(self):
        url=self.url_ori+self.stopRecord+'?type=1&vhost=__defaultVhost__&app=live&stream=stream'+str(self.id_stream)
        data_json = json.dumps(self.data)   
        response = requests.post(url, data=data_json, headers=self.headers)
        url=self.url_ori+self.getMp4RecordFile+'?vhost=__defaultVhost__&app=live&stream=stream'+str(self.id_stream)+'&period='+str(self.date_time.date())
        response = requests.post(url, data=data_json, headers=self.headers) 
        res=response.json()
        mp4_name=''
        if len(res['data']['paths'])==len(self.mp4_res)+1: #如果录制视频数多了一个
            for re in res['data']['paths']:
               mp4_state=0
               mp4_rename=''
               for re1 in self.mp4_res:
                   if re1==re:
                       mp4_state=1  #有相同名字的mp4
                   else :
                       mp4_rename=res['data']['rootPath']+re
               if mp4_state==0:
                   mp4_name=mp4_rename
        if mp4_name=='':  #排除因为接近24点，录制时间进入第二天
            date_time_new=datetime.now()
            url=self.url_ori+self.getMp4RecordFile+'?vhost=__defaultVhost__&app=live&stream=stream'+str(self.id_stream)+'&period='+str(date_time_new.date())
            response = requests.post(url, data=data_json, headers=self.headers) 
            res=response.json()
            if len(res['data']['paths'])==1:   #保存新一天的视频，数量应为1
                mp4_name=res['data']['paths'][0]
        if mp4_name=='':
            mp4_name=str(self.date_time)+'mp4 error'
        return mp4_name




